class_name Player extends CharacterBody2D

var speed:float = 100.0
var roll_speed := 145.0
var input_verctor := Vector2.ZERO
var last_input_verctor := Vector2.LEFT
var score := 0

@onready var animation_tree: AnimationTree = $AnimationTree
@onready var playback :AnimationNodeStateMachinePlayback= animation_tree.get("parameters/StateMachine/playback")

@export var stat:Stat
@onready var hurt_box: HurtBox = $HurtBox
@onready var blink_animation_player: AnimationPlayer = $BlinkAnimationPlayer
@onready var hurt_audio_stream_player: AudioStreamPlayer = $HurtAudioStreamPlayer
#@export var joystick:JoyStick

func _ready() -> void:
	hurt_box.hurt.connect(do_hit)
	stat.no_health.connect(die)

# 受到伤害时调用
func do_hit(other_hitbox:HitBox) -> void:
	if stat.health <= 0:
		return
	stat.health -= other_hitbox.damage
	hurt_audio_stream_player.play()
	blink_animation_player.play("blink")

# 玩家死亡时调用
func die() -> void:
	hide()
	remove_from_group("player")
	process_mode = Node.PROCESS_MODE_DISABLED

func add_health(amount: int) -> void:
	stat.health += amount

func add_score(amount: int) -> void:
	score += amount
	var score_label = get_tree().get_first_node_in_group("score_label")
	if score_label:
		score_label.text = "得分: " + str(score)

func _physics_process(_delta: float) -> void:
	var state = playback.get_current_node()

	match state:
		"moveState": move_state(_delta)
		"攻击状态": pass
		"翻滚状态": roll_state(_delta)
		
func move_state(delta: float) -> void:
	# 获取用户的输入，向量上下左右
	input_verctor = Input.get_vector("move_left","move_right","move_up","move_down")
	
	# 应用输入的速度到角色
	if input_verctor != Vector2.ZERO:
		last_input_verctor = input_verctor
		update_blend_position(input_verctor)

	# 如果按下攻击键，就切换攻击状态
	if Input.is_action_just_pressed("attack"):
		playback.travel("攻击状态")
	elif Input.is_action_just_pressed("roll"):
		playback.travel("翻滚状态")

	velocity =  input_verctor * speed
	move_and_slide()

#翻滚状态
func roll_state(delta: float) -> void:
	velocity = last_input_verctor.normalized() * roll_speed
	move_and_slide()

#更新状态机位置
func update_blend_position(verctor: Vector2) -> void:
	verctor = Vector2(verctor.x, -verctor.y)
	animation_tree.set("parameters/StateMachine/moveState/跑步状态/blend_position",verctor)
	animation_tree.set("parameters/StateMachine/moveState/站立状态/blend_position", verctor)
	animation_tree.set("parameters/StateMachine/攻击状态/blend_position", verctor)
	animation_tree.set("parameters/StateMachine/翻滚状态/blend_position", verctor)
